﻿// --------------
// 作者:Vitity
// --------------

namespace NICWebApi.Extensions.DynamicAPI.Filter;

/// <summary>
/// Swagger操作过滤器，用于自定义Swagger文档的生成
/// </summary>
public class SwaggerDocumentFilter : IDocumentFilter
{
    /// <summary>
    /// 将Swagger文档中的标签排序
    /// </summary>
    /// <param name="swaggerDoc">Swagger文档</param>
    /// <param name="context">文档过滤器上下文</param>
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        if (swaggerDoc == null || context == null)
            return;

        try
        {
            // 收集所有实际被接口引用的分组及其描述、顺序
            var actionMetas = Utils.GetAllActionMetas();
            
            if (actionMetas == null || !actionMetas.Any())
                return;

            // 保留原有的标签描述
            var existingTagDescriptions = swaggerDoc.Tags?
                .ToDictionary(t => t.Name, t => t.Description) ?? new Dictionary<string, string>();

            // 获取当前文档名称对应的标签
            var filteredTags = actionMetas
                .Where(meta => meta.Groups != null && meta.Groups.Any(o => string.Equals(o, context.DocumentName, StringComparison.OrdinalIgnoreCase)))
                .OrderBy(x => x.Order)
                .ThenBy(u => u.Controller)
                .Select(c => new OpenApiTag
                {
                    Name = c.Controller,
                    // 优先使用现有标签的描述，如果没有则使用空字符串
                    Description = existingTagDescriptions.TryGetValue(c.Controller, out var desc) ? desc : string.Empty
                })
                .GroupBy(t => t.Name) // 确保标签名称唯一
                .Select(g => g.First())
                .ToList();

            // 只有在有标签时才更新文档的标签集合
            if (filteredTags.Any())
            {
                swaggerDoc.Tags = filteredTags;
            }
        }
        catch (Exception ex)
        {
            // 记录异常但不中断Swagger文档生成
            System.Diagnostics.Debug.WriteLine($"Error in SwaggerDocumentFilter: {ex.Message}");
        }
    }
}